package com.sensetime.jv.controller;


import com.sensetime.jv.annotation.PermissionSyncHelper;
import com.sensetime.jv.annotation.RequirePermission;
import com.sensetime.jv.entity.ReturnWrapper;
import com.sensetime.jv.entity.UrlPermissionDTO;
import com.sensetime.jv.service.UrlPermissionService;
import com.sensetime.jv.util.JsonUtils;
import com.sensetime.jv.vo.request.ManualPermissionRequestVO;
import com.sensetime.jv.vo.request.UrlRolePermissionRespVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/feign") // 添加基础路径
@Slf4j
public class AuthFeignController {

    private final PermissionSyncHelper helper;
    private final UrlPermissionService urlPermissionService;

    public AuthFeignController(PermissionSyncHelper helper, UrlPermissionService urlPermissionService) {
        this.helper = helper;
        this.urlPermissionService = urlPermissionService;
    }



    @PostMapping("/sync/manual")
    @RequirePermission(description = "同步接口权限feign",whiteUrl = true)
    public ReturnWrapper<Void> syncPermissions(@RequestBody List<ManualPermissionRequestVO> list) {
        log.info("<<<<<<<<<<<<<同步url权限:{}<<<<<<<<<<", JsonUtils.writeValueAsString(list));
        List<UrlPermissionDTO> dtos = list.stream()
                .filter(dto -> !helper.shouldSkip(dto.getUrl(), dto.getMethod(), dto.getServletPath()))
                .map(dto -> {
                    UrlPermissionDTO d = new UrlPermissionDTO();
                    BeanUtils.copyProperties(dto, d);
                    return d;
                })
                .toList();
        helper.syncPermissionsBatchLock(dtos);

        return ReturnWrapper.success();
    }

    @PostMapping("/permission/list")
    public ReturnWrapper<List<UrlRolePermissionRespVO>> getAllPermissions(){
        return ReturnWrapper.success(urlPermissionService.getAllPermissions());
    }
}
